using System;
using System.IO;
using System.Text;
using FBroSharp;
using FBroSharp.Lib;
using FBroSharp.Event;
using FBroSharp.Value;
using FBroSharp.Const;
using FBroSharp.DataType;
using FBroSharp.Callback;

namespace HTTP请求拦截器
{
    /// <summary>
    /// 浏览器事件处理器 - 必须是单独文件
    /// </summary>
    public class BrowserEvent : FBroSharpBrowserEvent
    {
        private Form1 _form;

        public BrowserEvent(Form1 form)
        {
            _form = form;
        }

        /// <summary>
        /// 浏览器创建完成
        /// </summary>
        public override void OnAfterCreated(IFBroSharpBrowser browser, IFBroSharpDictionaryValue extrainfo)
        {
            _form.UpdateStatus($"浏览器已就绪 (ID: {browser.GetIdentifier()})");
            Console.WriteLine($"✅ 浏览器创建完成，ID：{browser.GetIdentifier()}");
        }

        /// <summary>
        /// URL地址变更
        /// </summary>
        public override void OnAddressChange(IFBroSharpBrowser browser, IFBroSharpFrame frame, string url)
        {
            if (frame.IsMain())
            {
                _form.UpdateAddressBar(url);
            }
        }

        /// <summary>
        /// 标题变更
        /// </summary>
        public override void OnTitleChange(IFBroSharpBrowser browser, string title)
        {
            _form.UpdateTitle(title);
        }

        /// <summary>
        /// 加载状态变更
        /// </summary>
        public override void OnLoadingStateChange(IFBroSharpBrowser browser, bool isLoading, bool canGoBack, bool canGoForward)
        {
            _form.UpdateNavigationButtons(canGoBack, canGoForward, isLoading);
        }

        /// <summary>
        /// 开始加载
        /// </summary>
        public override void OnLoadStart(IFBroSharpBrowser browser, IFBroSharpFrame frame, FBroSharpTransitionType transition_type)
        {
            if (frame.IsMain())
            {
                _form.UpdateStatus($"正在加载: {frame.GetURL()}");
                Console.WriteLine($"[Browser] 开始加载: {frame.GetURL()}");
            }
        }

        /// <summary>
        /// 加载完成
        /// </summary>
        public override void OnLoadEnd(IFBroSharpBrowser browser, IFBroSharpFrame frame, int httpStatusCode)
        {
            if (frame.IsMain())
            {
                _form.UpdateStatus($"加载完成 (HTTP {httpStatusCode})");
                Console.WriteLine($"[Browser] 加载完成: {frame.GetURL()} (HTTP {httpStatusCode})");
            }
        }

        /// <summary>
        /// 加载错误
        /// </summary>
        public override void OnLoadError(IFBroSharpBrowser browser, IFBroSharpFrame frame, 
            int errorCode, string errorText, string failedUrl)
        {
            if (frame.IsMain())
            {
                _form.UpdateStatus($"加载失败: {errorText}");
                Console.WriteLine($"[Browser] 加载错误: {errorText} ({errorCode})");
            }
        }

        /// <summary>
        /// ⚠️ CRITICAL: 阻止弹窗，在当前窗口打开
        /// </summary>
        public override bool OnBeforePopup(
            IFBroSharpBrowser browser, 
            IFBroSharpFrame frame, 
            string target_url, 
            string target_frame_name,
            FBroSharpWindowOpenDisposition target_disposition, 
            bool user_gesture, 
            FBroSharpPopupfeatures popupFeatures, 
            ref FBroSharpWindowsInfo windowInfo,
            ref FBroSharpBrowserSetting settings,
            ref bool no_javascript_access, 
            IFBroSharpUseExtraData user_settings)
        {
            // 在当前窗口打开链接
            frame.LoadURL(target_url);
            return true; // true = 阻止弹窗
        }

        /// <summary>
        /// ⚠️ CRITICAL: HTTP响应拦截 - 核心功能
        /// </summary>
        public override void GetResourceResponseFilter(
            IFBroSharpBrowser browser, 
            IFBroSharpFrame frame, 
            IFBroSharpRequest request, 
            IFBroSharpResponse response, 
            IFBroSharpResponseFilter set_filter)
        {
            string requestUrl = request.GetURL();
            string method = request.GetMethod();
            
            // 记录请求信息到Form1
            _form.LogHttpRequest(new HttpRequestInfo
            {
                Url = requestUrl,
                Method = method,
                StatusCode = response.GetStatus(),
                MimeType = response.GetMimeType(),
                Timestamp = DateTime.Now
            });

            // 创建响应拦截器
            FBroResponseFilterEvent callback = new FBroResponseFilterEvent(_form, requestUrl, method);
            set_filter.SetCallback(callback);
        }

        /// <summary>
        /// 浏览器关闭前
        /// </summary>
        public override void OnBeforeClose(IFBroSharpBrowser browser)
        {
            Console.WriteLine("浏览器关闭");
        }

        /// <summary>
        /// 是否可以关闭浏览器
        /// </summary>
        public override bool DoClose(IFBroSharpBrowser browser)
        {
            return false; // false = 允许关闭
        }
    }

    /// <summary>
    /// HTTP响应拦截器回调类
    /// </summary>
    public class FBroResponseFilterEvent : FBroSharpResponseFilterEvent
    {
        private Form1 _form;
        private string _url;
        private string _method;
        private MemoryStream _responseStream;
        private BinaryWriter _writer;

        public FBroResponseFilterEvent(Form1 form, string url, string method)
        {
            _form = form;
            _url = url;
            _method = method;
        }

        public override void Start(long flag) 
        {
            _responseStream = new MemoryStream();
            _writer = new BinaryWriter(_responseStream);
            Console.WriteLine($"[拦截器] 开始拦截: {_url}");
        }

        public override void End(long flag)
        {
            try
            {
                byte[] data = _responseStream.ToArray();
   
                if (data != null && data.Length > 0)
                {
                    // 记录响应数据到Form1
                    _form.LogHttpResponse(_url, _method, data);
                    
                    Console.WriteLine($"[拦截成功] URL: {_url}");
                    Console.WriteLine($"[拦截成功] 大小: {data.Length} 字节");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[拦截器] End错误: {ex.Message}");
            }
            finally
            {
                _responseStream?.Dispose();
                _responseStream = null;
                _writer = null;
            }
        }

        public override FBroSharpResponseFilterStatus Filter(
            long flag, 
            Stream dataIn, 
            out long dataInRead, 
            Stream dataOut, 
            out long dataOutWritten)
        {
            dataInRead = 0;
            dataOutWritten = 0;
            
            try
            {
                if (dataIn == null)
                {
                    return FBroSharpResponseFilterStatus.RESPONSE_FILTER_DONE;
                }

                // 计算可读取的数据量
                dataInRead = Math.Min(dataIn.Length, dataOut.Length);
                dataOutWritten = dataInRead;

                var readBytes = new byte[dataInRead];
                dataIn.Read(readBytes, 0, readBytes.Length);
                
                // ⚠️ 关键：确保数据立即传递给浏览器，避免阻塞
                dataOut.Write(readBytes, 0, readBytes.Length);
                dataOut.Flush();

                // ⚠️ 安全检查：避免内存溢出（限制10MB）
                if (_responseStream != null && _responseStream.Length > 10 * 1024 * 1024)
                {
                    Console.WriteLine($"[拦截器] 数据过大，停止收集: {_url}");
                    return FBroSharpResponseFilterStatus.RESPONSE_FILTER_DONE;
                }

                // 写入内存流保存数据
                _writer?.Write(readBytes);

                // 如果还有更多数据需要读取
                if (dataInRead < dataIn.Length)
                {
                    return FBroSharpResponseFilterStatus.RESPONSE_FILTER_NEED_MORE_DATA;
                }

                return FBroSharpResponseFilterStatus.RESPONSE_FILTER_DONE;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[拦截器] Filter错误: {ex.Message}");
                return FBroSharpResponseFilterStatus.RESPONSE_FILTER_ERROR;
            }
        }

        public override bool InitFilter(long flag)
        {
            // 返回true开始拦截
            return true;
        }
    }
}

